<?php
/**
 *
 * 项目模块加载入口
 *
 * @author     liang<lang@vip.deyi.com>
 * @since      2015年5月21日
 * @copyright  deyi.com
 */

namespace Apps\Acp;

use Phalcon\DiInterface;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt;

class Module implements ModuleDefinitionInterface
{

    public function registerAutoloaders(DiInterface $di = null)
    {
    }

    public function registerServices(DiInterface $di)
    {
        $selfModuleName = basename(__DIR__);
        $di->set(
            'dispatcher',
            function () use ($selfModuleName) {
                $dispatcher = new Dispatcher();
                $dispatcher->setDefaultNamespace("Apps\\$selfModuleName\\Controllers");

                return $dispatcher;
            },
            true
        );

        $di->set(
            'view',
            function () use ($selfModuleName) {

                $view = new View();
                $view->setViewsDir(ROOT_PATH . "/Apps/$selfModuleName/Views/");
                $view->registerEngines(
                    [
                        '.phtml' => function ($view, $di) {
                            $volt = new Volt($view, $di);

                            $volt->setOptions(
                                [
                                    'compiledPath' => function ($templatePath) {
                                        $compiledFilePath = str_replace('/', '_', $templatePath);

                                        return ROOT_PATH . '/data/compiled/' . $compiledFilePath . '.php';
                                    }
                                ]
                            );

                            //注册自定义函数方法
                            $compiler = $volt->getCompiler();
                            $compiler->addFunction('inarray', 'in_array');
                            $compiler->addFunction('keyexist', 'array_key_exists');
                            $compiler->addFunction('isarray', 'is_array');
                            $compiler->addFunction('the_end', 'end');
                            $compiler->addFunction('number_format', 'number_format');
                            $compiler->addFunction('count', 'count');

                            return $volt;
                        }
                    ]
                );

                return $view;
            }
        );
    }
}
